
from whiff import gateway
from whiff.middleware import misc
import time

class getItem(misc.utility):
    
    def __init__(self, page):
        self.page = page
        
    def __call__(self, env, start_response):
        env = env.copy()
        is_stub = env.get("STUB")
        if is_stub:
            env = self.stub(env)
        else:
            env = self.update(env)
        return self.deliver_page(self.page, env, start_response)
    
    def stub(self, env):
        env["pageList"] = [
            [ "FIRST_PAGE_NAME_STUB", "Stub Title For First Page" ],
            [ "SECOND_PAGE_NAME_STUB", "Stub Title For Second Page" ],
            [ "THIRD_PAGE_NAME_STUB", "Stub Title For Third Page" ]
            ]
        return env

    def update(self, env):
        storage = gateway.getResource(env, ["storage"])
        if storage is None:
            # no entries
            env["pageList"] = []
            return env
        entries = storage.values()
        namesAndSummaries = [ [e["Name"], e["Title"]] for e in entries ]
        namesAndSummaries.sort()
        env["pageList"] = namesAndSummaries
        ##pr "update returning", env
        return env

__middleware__ = getItem
